<?php

namespace App\Repositories\Manage;

use App\Models\Park;
use App\Models\Shop;
use App\Models\ShopMemberRole;
use App\Models\Supplier;
use App\Repositories\PictureMappingRepository;

class SupplierRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Supplier::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            if (isset($v['park_id']))
                $v['park_title'] = Park::query()->where("id", $v['park_id'])->value("title");

            if (isset($v['supplier_id']))
                $v['supplier_title'] = Shop::query()->where("id", $v['supplier_id'])->value("title");

            if (isset($v['store_time']))
                $v['store_time'] = json_decode($v['store_time'], true);

            $v['roleIds'] = ShopMemberRole::query()->where(['shop_id' => $v['id']])->pluck("role_id")->toArray();
        }

        return $res;
    }

    public function getOne($id = null)
    {
        $res = Supplier::query()->with("shop")->where("id", $id)->first();

        if (isset($res['store_time']))
            $res['store_time'] = json_decode($res['store_time'], true);

        if ($res["park_id"]) {
            $res['park_title'] = Park::query()->where("id", $res['park_id'])->value("title");
        }
        $res['role_id'] = ShopMemberRole::query()->where(['shop_id' => $res['id']])->pluck("role_id")->toArray();

        $pictures = (new PictureMappingRepository())->getMappingBySearch([
            'object_type' => "shop",
            'object_id' => $res['id']
        ]);

        $res['pictures'] = $pictures ?? null;
        $res['picture_ids'] = get_column($pictures, "picture_id");

        if ($res['base_shipping_price']) {
            $res['base_shipping_price'] = json_decode($res['base_shipping_price'], true);
        }

        return $res;
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);
        if (intval($id)) {
            Supplier::where("id", $id)->update($data);
            delRedis("shop_" . $id);
            return $id;
        } else {
            $res = Supplier::create($data);
            return $res['id'] ?? "";
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function deleteSupplier($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Supplier::where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

    /**
     * 获取类型
     */
    public function getOptions($type = null, $conditions = [])
    {
        return Supplier::query()->where('id', '>', 0)
            ->when(strlen($type), function ($q) use ($type) {
                return $q->where("type", intval($type));
            })
            ->when(!empty($conditions['shop_id']), function ($q) use ($conditions) {
                if (is_array($conditions['shop_id'])) {
                    return $q->whereIn("id", $conditions['shop_id']);
                } else {
                    return $q->where('id', "=", intval($conditions['shop_id']));
                }
            })
            ->orderBy("id", 'desc')
            ->get(['id', 'title'])
            ->toArray();
    }

    //获取店铺对应的分类 / 档口
    public function getSupplierOptions($shop_id = 0)
    {
        $shops = Supplier::query()
            ->when($shop_id, function ($q) use ($shop_id) {
                return $q->where("id", $shop_id);
            })
//            ->orderBy("sort", 'asc')
            ->orderBy("id", 'desc')
            ->get(['id', 'title'])
            ->toArray();

        foreach ($shops as $k => &$shop) {
            $shop['stalls'] = (new StallRepository())->getOptions($shop['id']);
            $shop['categories'] = (new ProductCategoryRepository())->getOptions($shop['id']);
        }

        return $shops;
    }

    /**
     * 更新会员标签
     * @param int $shop_id
     * @param array $roleIds
     */
    public function updateRole(int $shop_id = 0, $roleIds = [])
    {
        if (!$shop_id)
            return false;

        ShopMemberRole::query()->where(['shop_id' => $shop_id])->delete();
        if (empty($roleIds))
            return true;

        $data = [];
        foreach ($roleIds as $k => $role_id) {
            $data[] = [
                'shop_id' => intval($shop_id),
                'role_id' => intval($role_id),
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
            ];
        }
        ShopMemberRole::insert($data);

        return true;
    }

}
